# -*- coding: utf-8 -*-

from protocol import PyProtocol
from w.javascript.base import JSTranslator

class Error(Exception): pass

def testLType(obj):
    return not isinstance(obj,Link) and not isinstance(obj,LinkPtr)

class Link(JSTranslator):
    def __init__(self, *args, **kwargs):
        JSTranslator.__init__(self, *args, **kwargs)

    def __call__(self, *args, **kwargs):
        if kwargs:
            raise Error("Javascript doesn't support named params")
        def processArg(arg):
            if isinstance(arg, Link):
                return arg
            return PyProtocol.serialize(a)
        fargs = ','.join([processArg(a) for a in args])
        return Link("%s(%s)"%(self,fargs))

    def __getattribute__(self, fname):
        if hasattr(str.__init__(self), fname) or\
	    fname.startswith('__') and fname.endswith('__'):
            return str.__getattribute__(self, fname)
        return Link("%s.%s"%(self, fname))

    def __lshift__(self, obj):
        if testLType(obj):
            obj = PyProtocol.serialize(obj)
        return Link('%s = %s;'%(self, obj))

    def __add__(self, other):
        if testLType(other):
            return Link("%s+'%s'"%(self, other))
        return Link("%s+%s"%(self, other))

    def __mul__(self, other):
        if testLType(other):
            return Link("%s*'%s'"%(self, other))
        return Link("%s*%s"%(self, other))

    def __div__(self, other):
        if testLType(other):
            return Link("%s/'%s'"%(self, other))
        return Link("%s/%s"%(self, other))

    def __sub__(self, other):
        if testLType(other):
            return Link("%s-'%s'"%(self, other))
        return Link("%s-%s"%(self, other))

class StringLink(Link):
    def __str__(self):
        return "'%s'"%Link.__str__(self)

class LinkPtr(object):
    def __getattribute__(self, fname):
        if not fname.startswith('__') and not fname.endswith('__')\
	    and fname not in self.__dict__:
            return Link(fname)
        return object.__getattribute__(self,fname)

